const path = require('path');
const Sequelize = require('sequelize');
const fs = require('fs-extra');
const chalk = require('chalk');

// const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require('../config.json').mysql[env];

const sequelize = new Sequelize(
  config.database,
  config.username,
  config.password,
  {
    ...config,
    dialectOptions: {
      // Your mysql2 options here
    },
    // 连接池
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000,
    },
    // timezone: '+08:00', // 慢几小时就加几小时，快则减
    // logging: (...msg) => console.log(msg)
  },
);

/**
 * 验证数据库连接
 */
async function authenticateDatabaseConnection() {
  try {
    await sequelize.authenticate();
    console.log(chalk.green('%s Connection has been established successfully.'), '[sequelize]');
  } catch (error) {
    console.error(chalk.red('%s Unable to connect to the database:'), '[sequelize]');
    console.log('line 35', error.message);
    process.exit(1);
  }
}

/**
 * 注册models文件夹下除index.js所有的model
 */
async function registerModel() {
  try {
    const aFiles = await fs.readdir(path.join(__dirname, 'models'));
    aFiles
      .filter(file => file.indexOf('.') !== 0 && file.indexOf('sql-') >= 0 && file.slice(-3) === '.js')
      .forEach(item => {
        // register model
        require(path.resolve(__dirname, 'models', item))(sequelize);
        // sequelize.models[model.name] = model;
      });
  } catch (error) {
    console.log('line 58', error.message);
    process.exit(1);
  }
}

/**
 * 同步所有model
 */
function syncModel() {
  Object.keys(sequelize.models).forEach(modelName => {
    const model = sequelize.models[modelName];
    // 一次同步所有模型
    // sequelize.sync({ force: true });
    // 单个模型同步
    if (model) {
      model
        .sync({
          // 无参: 如果表不存在，則會創建表（如果已經存在，則不執行任何操作）
          // force: true, //-這將創建表，如果該表已經存在，則將其首先刪除
          alter: true, // -這將檢查數據庫中表的當前狀態（它具有哪些列，它們的數據類型等），然後在表中進行必要的更改以使其與模型匹配
        })
        .then(res => {
          // console.log(chalk.green('初始化完成'), res === model);
          if (syncModel.associate) {
            syncModel.associate(sequelize.models);
          }
        })
        .catch(error => {
          console.log('line 78', error.message);
          process.exit(1);
        });
    }
  });
}

// 斷開連接
// sequelize.close().then(() => {})

// User.drop();// 刪除與模型相關的表
// sequelize.drop();// 刪除所有表

/**
 * entry
 */
async function init() {
  await authenticateDatabaseConnection();
  if (env === 'development') return;
  await registerModel();
  syncModel();
}
// init();

module.exports = {
  sequelize,
  init,
};
